from app.extensions import SessionLocal
from app.models.Clas import Clas
from app.models.Student import Student

class ClasRepository():
    def __init__(self, db: SessionLocal):
        self.db = db

    def get_by_keyword(self, keyword):
        """
        根据关键字查询数据
        :param keyword: 关键字
        :return:
        """
        try:
            data = self.db.query(Clas).filter(Clas.name.like(f"%{keyword}%")).all()
            return data
        except:
            return []

    def get_clas_by_name(self,name):
        try:
            data = self.db.query(Clas).filter(Clas.name == name).one()
            return data
        except:
            return None

    def get_clas_by_id(self,id):
        try:
            data = self.db.query(Clas).filter(Clas.id == id).one()
            return data
        except:
            return None

    def add_clas(self, name):
        try:
            clas = Clas(name=name)
            self.db.add(clas)
            self.db.commit()
            return True
        except:
            return False

    def modify_clas(self, id, new_name):
        try:
            clas = self.get_clas_by_id(id)
            if not clas:
                print(f"未找到班级: {id}")
                return False
            clas.name = new_name
            self.db.commit()
            return True
        except Exception as e:
            self.db.rollback()
            print(f"更新班级失败: {e}")
            return False

    def delete_clas(self, id):
        try:
            clas = self.db.query(Clas).filter_by(id=id).first()
            if not clas:
                print(f"未找到班级：{id}")
                return False
            self.db.delete(clas)
            self.db.commit()
            return True
        except Exception as e:
            self.db.rollback()
            print(f"删除班级失败: {e}")
            return False

if __name__ == '__main__':
    from app.extensions import get_db
    with get_db() as db:
        repo = ClasRepository(db)
        data = repo.get_by_keyword("")
        for d in data:
            print(d)